package com.haitaoit.chengquan.module.login.enterprise;

import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.bean.RegistCompanyBeen;
import com.haitaoit.chengquan.module.center.model.ProvinceBase;
import com.haitaoit.chengquan.module.center.model.area;
import com.haitaoit.chengquan.module.center.model.city;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.pickerview.OptionsPopupWindow;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * Created by Administrator on 2016/10/9.
 */
public class RegistEnterInfoActivity extends BaseActivity {
    @ViewInject(R.id.enter_info_address)
    TextView enter_info_address;
    @ViewInject(R.id.enter_name)
    EditText enter_name;
    @ViewInject(R.id.enter_address_detail)
    EditText enter_address_detail;
    @ViewInject(R.id.enter_lxr_name)
    EditText enter_lxr_name;
    @ViewInject(R.id.enter_lxr_zhiwu)
    EditText enter_lxr_zhiwu;
    @ViewInject(R.id.next_go2)
    TextView next_go2;

    private List<ProvinceBase> province;
    private List<city>         city;
    private List<area>         region;

    private ArrayList<String>                       options1Items = new ArrayList<String>();
    private ArrayList<ArrayList<String>>            options2Items = new ArrayList<ArrayList<String>>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<ArrayList<ArrayList<String>>>();


    private String phone, pwd;

    private String address_ctiy;
    private double latitude  = 0;//维度
    private double longitude = 0;//经度
    private GeoCoder mSearch;
    private String   mCompay;
    private String   mCompayAdrees;
    private String   mCompayDatle;
    private String   mName;
    private String   mWorlk;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.fragment_regist_enter_info);
        ViewUtils.inject(this);


        phone = getIntent().getStringExtra("phone");
        pwd = getIntent().getStringExtra("pwd");

    }

    OnGetGeoCoderResultListener listener = new OnGetGeoCoderResultListener() {
        public void onGetGeoCodeResult(GeoCodeResult result) {
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {//获取地址
                // 没有检索到结果
                ToastUtils.showToast("亲，您的地址是无效的，请重新填写哦！");
                next_go2.setEnabled(true);

            } else {// 获取地理编码结果
                Log.e("tag", "result1:" + result.getAddress() + "====" + result.getLocation().latitude + "-----" + result.getLocation().longitude);
                latitude = result.getLocation().latitude;
                longitude = result.getLocation().longitude;
                // 发布
                httpGetUser_registered_enterprise();
            }
        }

        @Override
        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {// 获取经纬度
            if (reverseGeoCodeResult == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
                //没有找到检索结果
            } else {// 获取反向地理编码结果
                Log.e("tag", "reverseGeoCodeResult1:" + reverseGeoCodeResult.toString());
            }
        }
    };


    @OnClick({R.id.left, R.id.enter_info_addressll, R.id.next_go2})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.left:
                finish();
                break;
            case R.id.enter_info_addressll:
                // 收起键盘
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

                options1Items = new ArrayList<String>();
                options2Items = new ArrayList<ArrayList<String>>();
                options3Items = new ArrayList<ArrayList<ArrayList<String>>>();
                InputStream inputStream = getResources().openRawResource(R.raw.region);
                province(inputStream);
                // 地址选择器
                OptionsPopupWindow pwOptions = new OptionsPopupWindow(this, "选择地区");
                // 三级联动效果
                pwOptions.setPicker(options1Items, options2Items, options3Items, true);
                // 设置默认选中的三级项目
                pwOptions.setSelectOptions(0, 0, 0);
                // 监听确定选择按钮
                pwOptions.setOnoptionsSelectListener(new OptionsPopupWindow.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3) {
                        // 返回的分别是三个级别的选中位置
                        String tx = options1Items.get(options1) + ","
                                + options2Items.get(options1).get(option2) + ","
                                + options3Items.get(options1).get(option2).get(options3);
                        enter_info_address.setText(tx);
                        address_ctiy = options1Items.get(options1);
                    }
                });
                pwOptions.showAtLocation(LayoutInflater.from(this).inflate(R.layout.fragment_regist_enter_info, null),
                        Gravity.BOTTOM, ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
                break;
            case R.id.next_go2:
                next_go2.setEnabled(false);
                mCompay = enter_name.getText().toString().trim();
                mCompayAdrees = enter_info_address.getText().toString().trim();
                mCompayDatle = enter_address_detail.getText().toString().trim();
                mName = enter_lxr_name.getText().toString().trim();
                mWorlk = enter_lxr_zhiwu.getText().toString().trim();
                if ("".equals(mCompay)) {
                    ToastUtils.showToast("请输入公司名称！");
                    next_go2.setEnabled(true);
                    return;
                } else if ("".equals(mCompayAdrees)) {
                    ToastUtils.showToast("请选择公司地址！");
                    next_go2.setEnabled(true);
                    return;
                } else if ("".equals(mCompayDatle)) {
                    ToastUtils.showToast("请输入详细地址！");
                    next_go2.setEnabled(true);
                    return;
                } else if ("".equals(mName)) {
                    ToastUtils.showToast("请输入联系人姓名！");
                    next_go2.setEnabled(true);
                    return;
                } else if ("".equals(mWorlk)) {
                    ToastUtils.showToast("请输入联系人职务！");
                    next_go2.setEnabled(true);
                    return;
                } else {
                    // 获取经纬度
                    mSearch = GeoCoder.newInstance();
                    mSearch.geocode(new GeoCodeOption().city(address_ctiy).address(enter_address_detail.getText().toString()));
                    mSearch.setOnGetGeoCodeResultListener(listener);
                }
                break;
        }
    }

    private void httpGetUser_registered_enterprise() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("phone", phone);
        map.put("pwd", pwd);
        map.put("name", mCompay);
        map.put("area", mCompayAdrees);
        map.put("address", mCompayDatle);
        map.put("contact", mName);
        map.put("contact_position", mWorlk);
        map.put("longitude", longitude + "");
        map.put("latitude", latitude + "");
        final String sign = GetSign.getSign(map);
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpUtils
                        .get()
                        .url(Constant.GetUser_registered_enterprise)
                        .addParams("phone", phone)
                        .addParams("pwd", pwd)
                        .addParams("name", mCompay)
                        .addParams("area", mCompayAdrees)
                        .addParams("address", mCompayDatle)
                        .addParams("contact", mName)
                        .addParams("contact_position", mWorlk)
                        .addParams("longitude", longitude + "")
                        .addParams("latitude", latitude + "")
                        .addParams("sign", sign)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                ToastUtils.showToast("注册失败！");
                                next_go2.setEnabled(true);
                            }

                            @Override
                            public void onResponse(String response, int id) {

                                next_go2.setEnabled(true);
                                Gson gson = new Gson();
                                RegistCompanyBeen been = gson.fromJson(response, RegistCompanyBeen.class);
                                if (been == null) {
                                    ToastUtils.showToast("注册失败");
                                    return;
                                }
                                if (!TextUtils.equals("0",been.getErrCode())){
                                    ToastUtils.showToast(been.getErrMsg());
                                    return;
                                }

                                if (TextUtils.equals("0",been.getErrCode())) {
                                    ToastUtils.showToast(been.getErrMsg());
                                    startActivity(new Intent(RegistEnterInfoActivity.this, RegistEnterSuccessActivity.class));
                                    finish();
                                }
                            }
                        });
            }
        }).start();
    }

    /**
     * @param inputStream
     * @tab 解析从本地获取的json
     */
    private void province(InputStream inputStream) {
        String a = getString(inputStream);
        try {
            JSONObject jsondata = new JSONObject(a);
            Gson gson = new Gson();
            province = gson.fromJson(jsondata.getString("data"),
                    new TypeToken<List<ProvinceBase>>() {
                    }.getType());
            //            Log.e("tag", province.toString());
            ArrayList<String> options2Items_i = null;
            ArrayList<ArrayList<String>> options3Items_j = null;
            for (int i = 0; i < province.size(); i++) {
                options1Items.add(province.get(i).getName());
                city = province.get(i).getCity();
                options2Items_i = new ArrayList<String>();
                options3Items_j = new ArrayList<ArrayList<String>>();
                for (int j = 0; j < city.size(); j++) {
                    options2Items_i.add(city.get(j).getName());
                    region = city.get(j).getArea();
                    ArrayList<String> options3Items_j_j2 = new ArrayList<String>();
                    for (int j2 = 0; j2 < region.size(); j2++) {
                        options3Items_j_j2.add(region.get(j2).getName());
                    }
                    options3Items_j.add(options3Items_j_j2);
                }
                options2Items.add(options2Items_i);
                options3Items.add(options3Items_j);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public static String getString(InputStream inputStream) {
        InputStreamReader inputStreamReader = null;
        try {
            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        BufferedReader reader = new BufferedReader(inputStreamReader);
        StringBuffer sb = new StringBuffer("");
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

}
